<template>
  <view>
    <van-uploader
      :file-list="fileList"
      :capture="capture"
      :max-count="maxCount"
      :max-size="maxSize"
      :upload-icon="uploadIcon"
      @after-read="afterRead"
      @delete="remove"
    />
  </view>
</template>

<script>
import Taro from '@tarojs/taro'
import {deepClone} from '../../utils'

export default {
  name: 'UploadImage',
  props: {
    value: {
      type: String,
      required: false,
      default: undefined
    },
    uploadIcon: {
      type: String,
      required: false,
      default: 'photograph'
    },
    capture: {
      type: String,
      required: false,
      default: undefined
    },
    maxCount: {
      type: Number,
      required: false,
      default: 9
    },
    maxSize: {
      type: Number,
      required: false,
      default: 2*1024*1024
    },
    afterUpload: {
      type: Object,
      required: false,
      default: undefined
    }
  },
  data() {
    return {
      fileList: []
    }
  },
  // watch: {
  //   value: {
  //     immediate: true,
  //     handler(val) {
  //       this.fileList = []
  //       if (this.isNull(val)) {
  //         this.fileList = []
  //         return
  //       }
  //       val.split(',').forEach(item => {
  //         this.fileList.push({ url: item })
  //       })
  //       console.log('this.fileList', this.fileList)
  //     }
  //   }
  // },
  methods: {
    reset() {
      this.fileList = []
      this.emit()
    },
    afterRead(event) {
      this.fileUpload(event.detail.file)
    },
    fileUpload(file) {
      const _this = this
      Taro.uploadFile({
        url: 'http://localhost:8082//json/oss/upload', // 仅为示例，非真实的接口地址
        filePath: file.url,
        name: 'file',
        formData: { user: 'test' },
        success(res) {
          const data = JSON.parse(res.data)
          // 上传完成需要更新 fileList
          _this.fileList = _this.fileList.concat([{url: data.data}])
          _this.emit()
        },
      })
    },
    remove(event) {
      console.log('event', event)
      const list  = this.fileList
      list.splice(event.detail.index, 1)
      this.fileList = deepClone(list)
      this.emit()
    },
    emit() {
      const imageUrlList = []
      this.fileList.forEach(item => {
        imageUrlList.push(item.url)
      })
      this.$emit('input', imageUrlList.join(','))
    }

  }
}
</script>

<style scoped>

</style>
